/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.driving.core.exception.DrivingException;
import com.driving.core.util.Response;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统异常处理
 *
 * @author SAGITTAR
 * @since 2017
 */
@Slf4j
@RestControllerAdvice(annotations = { RestController.class, Controller.class })
public class DrivingCoreAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        if (body instanceof Response) {
            return body;
        }
        return Response.success(body);
    }

    @ExceptionHandler
    public Response<?> handleDrivingException(DrivingException e) {
        log.error(e.getLocalizedMessage(), e);
        return Response.failure(e);
    }
}
